#ifdef MU_LICENSING
#include "include/licensinguserinfo.h"

#include <QDebug>

namespace
{

const QString RootTag = "licenserequest";
const QString VersionAttr = "ver";
const QString CurrentVersion = "1.0";

const QString HostNameTag = "host";
const QString OSTag = "os";
const QString UserNameTag = "user";
const QString TimeUtcTag = "time";  //utc
const QString MacCollectionTag = "macs";
const QString MacEntityTag = "mac";

void addElement(QDomDocument& doc, QDomElement& parent, const QString& tagName, const QString& text)
{
	QDomElement elem = doc.createElement(tagName);
	elem.appendChild(doc.createTextNode(text));
	parent.appendChild(elem);
}

template <class C>
void readTag(const QDomElement& parent, C& obj, const QString& tagName,
			 void (C::*setter)(const QString&))
{
	QDomElement elem = parent.firstChildElement(tagName);
	if (elem.isNull())
		return;

	(obj.*setter)(elem.text());
}

}


LicensingUserInfo::LicensingUserInfo()
{
	_timeUtc = QDateTime::currentDateTimeUtc();
}


void LicensingUserInfo::writeTo(QDomDocument& doc) const
{
	QDomElement root = doc.createElement(RootTag);
	doc.appendChild(root);

	root.setAttribute(VersionAttr, CurrentVersion); //for compatibiity purposes in future

	addElement(doc, root, HostNameTag, hostName());
	addElement(doc, root, OSTag, OSName());
	addElement(doc, root, UserNameTag, userName());
	addElement(doc, root, TimeUtcTag, timeUtc().toString(Qt::ISODate));

	QDomElement addresses = doc.createElement(MacCollectionTag);
	root.appendChild(addresses);

	foreach (QString macAddr, macAddresses())
		addElement(doc, addresses, MacEntityTag, macAddr);
}


void LicensingUserInfo::readFrom(const QDomDocument& doc)
{
	QDomElement root = doc.documentElement();

	//we do not handle version now so we do not deserialize it yet.

	readTag(root, *this, HostNameTag, &LicensingUserInfo::setHostName);
	readTag(root, *this, OSTag, &LicensingUserInfo::setOSName);
	readTag(root, *this, UserNameTag, &LicensingUserInfo::setUserName);

	QDomElement elem;

	//reading time
	elem = root.firstChildElement(TimeUtcTag);
	if (!elem.isNull())
		setTimeUtc(QDateTime::fromString(elem.text(), Qt::ISODate));

	//reading mac addresses
	elem = root.firstChildElement(MacCollectionTag);
	if (!elem.isNull())
	{
		QDomElement macElem = elem.firstChild().toElement();

		while (!macElem.isNull())
		{
			_macAddresses.push_back(macElem.text());
			macElem = macElem.nextSibling().toElement();
		}
	}
}
#endif